package com.gitee.ly;

import com.gitee.ly.model.ServiceInfo;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.cloud.model.Discovery;
import org.noear.solon.cloud.model.Instance;
import org.noear.solon.core.AppContext;

import java.net.URI;

//每一个NamiClient都对应一个自己的 Discovery
@Slf4j
public class DynamicDiscover extends Discovery {
    private String serviceName;
    private DiscoverAndLoadBalancer discoverAndLoadBalancer;

    public DynamicDiscover(String group, String serviceName, AppContext appContext) {
        super(group, serviceName);
        this.serviceName = serviceName;
        appContext.getBeanAsync(DiscoverAndLoadBalancer.class, (DiscoverAndLoadBalancer discoverAndLoadBalancer) -> {
            this.discoverAndLoadBalancer = discoverAndLoadBalancer;
        });
    }

    @Override
    public int clusterSize() {
        //这里不代表集群数量1，是为了跳过solon的校验。让方法可以调用到 instanceGet()获取RPC服务
        return 1;
    }

    @Override
    public Instance instanceGet(int index, int port) {
        ServiceInfo chooseOne = this.discoverAndLoadBalancer.chooseOne(this.serviceName);
        if (chooseOne == null) {
            throw new RuntimeException(String.format("Light-Registry serviceName：[%s] NO Find Provider", this.serviceName));
        }
        String newUrl = String.format("%s://%s:%s", chooseOne.getSchema(), chooseOne.getIp(), chooseOne.getPort());
        log.info(String.format("Light-Registry serviceLoadBalance：[%s] (transfer to ->) %s ", this.serviceName, newUrl));
        Instance dynamicInstance = new Instance(this.serviceName, chooseOne.getIp(), chooseOne.getPort()).protocol(chooseOne.getSchema());
        return dynamicInstance;
    }
}
